package com.auth.aspect;

import cn.hutool.core.util.StrUtil;
import com.auth.Utils.LoginUserHelper;
import com.auth.Utils.ServletUtils;
import com.auth.annotation.PreAuthorize;
import com.auth.common.BaseException;
import com.auth.constant.CacheConstants;
import com.auth.constant.Constants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 自定义权限鉴权
 *
 */
@Aspect
@Component
public class PreAuthorizeAspect {

//    @Autowired
//    private LoginUserHelper loginUserHelper;

    // 配置织入点，加了权限注解的地方
    @Around("@annotation(com.auth.annotation.PreAuthorize)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        // 判断是不是内部调用
        String headerValue = ServletUtils.getHeader(CacheConstants.FEIGN_HEAD);
        if (!StrUtil.isEmpty(headerValue)) {
            if ("true".equals(headerValue)) {
                return point.proceed();
            }
        }

        // 外部请求需要鉴权
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
        if (annotation == null) {
            // 没有权限注解的直接让目标方法执行
            return point.proceed();
        } else {
            if (StrUtil.isEmpty(LoginUserHelper.getToken())) {
                throw new BaseException("鉴权异常：令牌不能为空!"+ annotation.hasPermi());
            }
//            LoginUser loginUser = loginUserHelper.getLoginUser();
//            if (loginUser == null) {
//                throw new BaseException("鉴权异常：没有登录!" + annotation.hasPermi());
//            }
//            if (!hasPermi(loginUser.getPermissions(), annotation.hasPermi())) {
//                throw new BaseException(BaseExceptionCodes.FORBIDDEN.getCode(), "当前用户缺少权限："+ annotation.hasPermi());
//            }
//
//            if (!hasRole(loginUser.getRoles(), annotation.hasRole())) {
//                throw new BaseException("当前用户缺少角色："+ annotation.hasRole());
//            }
        }
        return point.proceed();
    }

    /**
     * 验证是否具备某权限
     *
     * @return 用户是否具备某权限
     */
    private boolean hasPermi(Collection<String> authorities, String permission) {
        if (StrUtil.isEmpty(permission)) {
            return true;
        }
        if (CollectionUtils.isEmpty(authorities)) {
            return false;
        }
//        todo
//        return authorities.stream().filter(StrUtil::hasText)
//                .anyMatch(x -> Constants.ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
        return true;
    }
    
    

    /**
     * 验证是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    private boolean hasRole(Collection<String> roles, String role) {
        if (StrUtil.isEmpty(role)) {
            return true;
        }
        if (CollectionUtils.isEmpty(roles)) {
            return false;
        }
        for (String roleKey : roles) {
            if (Constants.SUPER_ADMIN.equals(roleKey) || roleKey.equals(role)) {
                return true;
            }
        }
        return false;
    }

}
